<!--
 * @Author: xuman
 * @Date: 2020-05-25 16:46:19
 * @LastEditors: xuman
 * @LastEditTime: 2020-07-09 10:23:45
-->
<template>
  <el-dialog
    title="模型导入"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    append-to-body
    :visible="true"
    :before-close="handleClose"
  >
    <el-form
      label-width="100px"
      :rules="rules"
      :model="modelForm"
      ref="modelForm"
    >
      <el-form-item label="模型文件:">
        <input type="file" accept="pmml" @change="handleUpload" />
      </el-form-item>
      <el-form-item label="模型CODE:" prop="modelCode">
        <el-input
          v-model="modelForm.modelCode"
          placeholder="仅支持英文、数字及下划线,64个字符以内,创建后不可修改"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="handleClose">取消</el-button>
      <el-button size="mini" type="primary" @click="handleSubmit">
        导入
      </el-button>
    </div>
  </el-dialog>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { Upload, Form } from 'element-ui'
import { isValidName } from '@/utils/validate'
import * as Api from '@/api/risksystem/feature/model'

const validateCode = (rule: any, value: string, callback: Function) => {
  if (!value) {
    callback(new Error('请输入模型CODE'))
  } else if (!isValidName(value)) {
    callback(new Error('只能输入英文、数字、下划线'))
  } else if (value.length > 64) {
    callback(new Error('不能超过64个字符'))
  } else {
    callback()
  }
}

@Component({})
export default class AddModel extends Vue {
  @Prop() getList!: Function

  private file: any = ''
  private modelForm: any = {
    modelCode: ''
  }
  private rules: any = {
    modelCode: [{ required: true, validator: validateCode, trigger: 'blur' }]
  }

  private handleUpload(event: any) {
    const files = event.target.files || event.dataTransfer.files
    if (!files.length) {
      this.file = ''
      return
    }
    this.file = files[0]
  }

  // 提交
  private handleSubmit() {
    if (!this.file) return this.$message.warning('请选择上传文件！')
    ;(this.$refs.modelForm as Form).validate(async (valid: boolean) => {
      if (valid) {
        const { modelCode } = this.modelForm
        const formData = new FormData()
        formData.append('file', this.file)
        formData.append('modelCode', modelCode)
        await Api.addModel(formData)
        this.$message.success('添加成功！')
        this.handleClose()
        this.getList()
      }
    })
  }

  private handleClose() {
    this.$emit('handleClose')
  }
}
</script>
<style lang="scss" scoped>
.el-dialog {
  .el-input {
    width: 480px;
  }
}
</style>
